﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace CommandLib
{
    /// <summary>
    /// INI文件操作
    /// </summary>
   public class OperateIniFile
    {
        #region API函数声明
        //返回0表示失败，非0为成功
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key,
            string val, string filePath);
        //返回取得字符串缓冲区的长度
        [DllImport("kernel32")]
        private static extern long GetPrivateProfileString(string section, string key,
            string def, StringBuilder retVal, int size, string filePath);


        #endregion

        #region 读Ini文件
       /// <summary>
       /// 读取INI配制文件
       /// </summary>
       /// <param name="Section">区域块名</param>
       /// <param name="Key">键</param>
       /// <param name="NoText">值</param>
       /// <param name="iniFilePath">文件路径</param>
       /// <returns>反回值</returns>
        public static string ReadIniData(string Section, string Key, string iniFilePath)
        {
            if (File.Exists(iniFilePath))
            {
                string NoText="";
                StringBuilder temp = new StringBuilder(1024);
                GetPrivateProfileString(Section, Key, NoText, temp, 1024, iniFilePath);
                return temp.ToString();
            }
            else
            {
                return String.Empty;
            }
        }

        #endregion
        #region 写Ini文件
        /// <summary>
        /// 写入INI配制文件
        /// </summary>
        /// <param name="Section">区域块名</param>
        /// <param name="Key">键</param>
        /// <param name="NoText">值</param>
        /// <param name="iniFilePath">文件路径</param>
        /// <returns>反回值</returns>
        public static bool WriteIniData(string Section, string Key, string Value, string iniFilePath)
        {
            try
            {
                if (!File.Exists(iniFilePath))
                {
                    String dir = iniFilePath.Substring(0, iniFilePath.LastIndexOf('\\'));
                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }
                    var ini = File.Create(iniFilePath);
                    ini.Close();
                }
                long OpStation = WritePrivateProfileString(Section, Key, Value, iniFilePath);
                return OpStation == 0;
            }
            catch (Exception)
            {
                return false;
            }
           
        }

        #endregion

    }

}
